﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.TextMining.Collapse
{
    /// <summary>
    /// 
    /// </summary>
    public partial class FuzzyGroupingEditor : Form, IComponentEditor
    {

        #region fields
        private Object _ActivityNode;
        private FuzzyGroupingComponent _FuzzyGroupComponent;
        #endregion

        /// <summary>
        /// 
        /// </summary>
        public FuzzyGroupingEditor()
        {
            InitializeComponent();
        }

        #region IComponentEditor Members

        public event UpdateComponentSettings UpdateComponentSettingEvent;

        public object OwnerActivityNode
        {
            get
            {
                return this._ActivityNode;
            }
            set 
            {
                this._ActivityNode = value;
            }
        }

        public Type WorkflowComponentType
        {
            get
            {
                return typeof (FuzzyGroupingComponent);
            }
        }

        public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents,
                                 object activityNode, WorkflowComponentBase wfComponent)
        {
            this._ActivityNode = activityNode;
            this._FuzzyGroupComponent = (FuzzyGroupingComponent) wfComponent;

            this.txt_ConnStr.Text = this._FuzzyGroupComponent.ConnStr;
            this.PopulateSchemas(this._FuzzyGroupComponent.ConnStr);
            this.PopulateTables(this._FuzzyGroupComponent.ConnStr, this.cbo_Schemas.Text);
            string schemaName = string.Empty;
            string tblName = this._FuzzyGroupComponent.TableName;
            if(tblName.IndexOf(".")>0)
            {
                schemaName = tblName.Substring(0, tblName.IndexOf("."));
                tblName = tblName.Substring(tblName.IndexOf(".") + 1);
            }
            if(this.cbo_Schemas.Items.Count>0 && (!string.IsNullOrEmpty(schemaName)))
            {
                for(int i=0;i<this.cbo_Schemas.Items.Count;i++)
                {
                    if(this.cbo_Schemas.Items[i].ToString()==schemaName)
                    {
                        this.cbo_Schemas.SelectedIndex = i;
                        break;
                    }
                }
            }
            if(this.cbo_Table.Items.Count>0 && (!string.IsNullOrEmpty(tblName)))
            {
                for(int i=0;i<this.cbo_Table.Items.Count;i++)
                {
                    if (this.cbo_Table.Items[i].ToString() == tblName)
                    {
                        this.cbo_Table.SelectedIndex = i;
                        break;
                    }
                }
            }
            if(this.cbo_Table.SelectedIndex <0 && (!string.IsNullOrEmpty(this._FuzzyGroupComponent.TableName)))
            {
                this.cbo_Table.Text = this._FuzzyGroupComponent.TableName;
            }
            if(this.cbo_Field.Items.Count>0 && (!string.IsNullOrEmpty(this._FuzzyGroupComponent.FieldName)))
            {
                for(int i=0;i<this.cbo_Field.Items.Count;i++)
                {
                    if(this.cbo_Field.Items[i].ToString()==this._FuzzyGroupComponent.FieldName)
                    {
                        this.cbo_Field.SelectedIndex = i;
                        break;
                    }
                }
            }
            if(this.cbo_Field.SelectedIndex<0 && (!string.IsNullOrEmpty(this._FuzzyGroupComponent.FieldName)))
            {
                this.cbo_Field.Text = this._FuzzyGroupComponent.FieldName;
            }
            if (this.cbo_IDField.Items.Count > 0 && (!string.IsNullOrEmpty(this._FuzzyGroupComponent.IDFieldName)))
            {
                for (int i = 0; i < this.cbo_IDField.Items.Count; i++)
                {
                    if (this.cbo_IDField.Items[i].ToString() == this._FuzzyGroupComponent.IDFieldName)
                    {
                        this.cbo_IDField.SelectedIndex = i;
                        break;
                    }
                }
            }
            if (this.cbo_IDField.SelectedIndex < 0 && (!string.IsNullOrEmpty(this._FuzzyGroupComponent.IDFieldName)))
            {
                this.cbo_IDField.Text = this._FuzzyGroupComponent.IDFieldName;
            }

            this.ck_Persist.Checked = this._FuzzyGroupComponent.PersistToTable;
            this.txt_OutputTable.Text = this._FuzzyGroupComponent.OutputTableName;
            this.trk_Threshold.Value = (int) (this._FuzzyGroupComponent.SimilarityThreshold*100);
        }

        private void PopulateTables(string connStr, string schemaName)
        {
            this.cbo_Table.Items.Clear();
            this.cbo_Table.SelectedIndex = -1;
            this.cbo_Table.Text = string.Empty;

            if(!string.IsNullOrEmpty(connStr))
            {
                string[] tblNames = DbUtil.GetTableNames(DataProviderType.MSSQL, schemaName, connStr);
                if(tblNames !=null && tblNames.Length>0)
                {
                    foreach(string tblName in tblNames)
                    {
                        this.cbo_Table.Items.Add(tblName);
                    }
                }
            }
        }

        public void SaveSettings()
        {
            this._FuzzyGroupComponent.ConnStr = this.txt_ConnStr.Text;
            this._FuzzyGroupComponent.TableName = this.cbo_Table.Text;
            if(this.cbo_Schemas.SelectedIndex >=0)
            {
                this._FuzzyGroupComponent.TableName = this.cbo_Schemas.Text + "." + this.cbo_Table.Text;
            }
            this._FuzzyGroupComponent.IDFieldName = this.cbo_IDField.Text;
            this._FuzzyGroupComponent.FieldName = this.cbo_Field.Text;
            this._FuzzyGroupComponent.PersistToTable = this.ck_Persist.Checked;
            this._FuzzyGroupComponent.OutputTableName = this.txt_OutputTable.Text;
            this._FuzzyGroupComponent.SimilarityThreshold = (double) this.trk_Threshold.Value/100;
        }

        public TestResult Test()
        {
            this.SaveSettings();

            FuzzyGroupingInstruction instruction = new FuzzyGroupingInstruction(this._FuzzyGroupComponent.ComponentID,
                                                                                Guid.Empty,
                                                                                this._FuzzyGroupComponent.ConnStr,
                                                                                this._FuzzyGroupComponent.TableName,
                                                                                this._FuzzyGroupComponent.IDFieldName,
                                                                                this._FuzzyGroupComponent.FieldName,
                                                                                this._FuzzyGroupComponent.
                                                                                    SimilarityThreshold,
                                                                                this._FuzzyGroupComponent.PersistToTable,
                                                                                this._FuzzyGroupComponent.
                                                                                    OutputTableName);
            //FuzzyGroupingWorker worker = new FuzzyGroupingWorker();
            //worker.SetInstruction(Guid.NewGuid(),instruction);
            //try
            //{
            //    worker.DoWork();
            //    return new TestResult(true, "Success");
            //}
            //catch(Exception ex)
            //{
            //    return new TestResult(false,ex.ToString());
            //}

            return new TestResult(true, "Not implemented");
        }

        #endregion

        private void FuzzyGroupingEditor_Load(object sender, EventArgs e)
        {

        }

        private void cbo_Table_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(this.txt_ConnStr.Text) && this.cbo_Table.SelectedIndex>=0)
            {
                TableColumn[] cols = DbUtil.GetTableColumns(DataProviderType.MSSQL, this.txt_ConnStr.Text,
                                                            this.cbo_Schemas.Text,
                                                            this.cbo_Table.Text);
                this.cbo_Field.Items.Clear();
                this.cbo_Field.SelectedIndex = -1;
                this.cbo_Field.Text = string.Empty;
                this.cbo_IDField.Items.Clear();
                this.cbo_IDField.SelectedIndex = -1;
                this.cbo_IDField.Text = string.Empty;
                if(cols !=null && cols.Length>0)
                {
                    foreach(TableColumn col in cols)
                    {
                        this.cbo_Field.Items.Add(col.ColumnName);
                        this.cbo_IDField.Items.Add(col.ColumnName);
                    }
                }
            }
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            if(this.UpdateComponentSettingEvent !=null)
            {
                this.UpdateComponentSettingEvent(this._ActivityNode, this._FuzzyGroupComponent);
            }
            this.Close();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_Test_Click(object sender, EventArgs e)
        {
            TestResult result = this.Test();
            MessageBox.Show(result.Message, result.Succeed.ToString());
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            if(this.cbo_Schemas.SelectedIndex <0)
            {
                this.PopulateSchemas(this.txt_ConnStr.Text);
                this.PopulateTables(this.txt_ConnStr.Text, this.cbo_Schemas.Text);
            }
            else
            {
                this.PopulateTables(this.txt_ConnStr.Text, this.cbo_Schemas.Text);
            }
        }

        private void PopulateSchemas(string connStr)
        {
            this.cbo_Schemas.Items.Clear();
            this.cbo_Schemas.SelectedIndex = -1;
            this.cbo_Schemas.Text = string.Empty;
            string[] schemaNames = DbUtil.GetSchemaNames(DataProviderType.MSSQL, connStr);
            if(schemaNames !=null && schemaNames.Length>0)
            {
                foreach(string schemaName in schemaNames)
                {
                    this.cbo_Schemas.Items.Add(schemaName);
                }
                this.cbo_Schemas.SelectedIndex = 0;
            }
        }

        private void cbo_Schemas_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void trk_Threshold_Scroll(object sender, EventArgs e)
        {
            this.lbl_Threshold.Text = ((double) this.trk_Threshold.Value/100).ToString();
        }
    }
}
